package com.mszlu.blog.admin.service.security;

import com.mszlu.blog.admin.entity.Admin;
import com.mszlu.blog.admin.entity.Permission;
import com.mszlu.blog.admin.service.AdminService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class AuthService {

    @Autowired
    private AdminService adminService;

    public boolean auth(HttpServletRequest request, Authentication authentication){
        //权限认证
        //请求路径
        String requestURI = request.getRequestURI();

        //判断是否登录
        Object principal = authentication.getPrincipal();
        if (principal==null || "anonymousUser".equals(principal)){
            //如果为空,或为匿名用户
            //未登录
            return false;
        }

        UserDetails userDetails = (UserDetails) principal;
        String username = userDetails.getUsername();
        Admin admin = adminService.findAdminByUserName(username);

        //如果数据库中无该用户
        if (admin == null) {
            return false;
        }
        //如果id为1则为超级管理员
        if (1 == admin.getId()) {
            return true;
        }

        List<Permission> permissionList = this.adminService.findPermissionByAdminId(admin.getId());
        requestURI = StringUtils.split(requestURI,"?")[0];
        for (Permission permission : permissionList) {
            if (requestURI.equals(permission.getPath())) {
                return true;
            }
        }
        return false;
    }

}
